# coding: utf-8

from flask import Blueprint, render_template, redirect, url_for, flash
from functools import wraps
from flask_login import current_user
from db.models import SysUserRole, SysRolePerm, SysRole, SysPerm
from const import roles_data
from log import logger

def get_user_permissions():
    permissions = set()
    roles = SysUserRole.query.filter_by(user_id=current_user.id).all()
    for role in roles:
        role_perms = SysRolePerm.query.filter_by(role_id=role.role_id).all()
        for role_perm in role_perms:
            permissions.add(role_perm.perm_key)
    return permissions

def permission_required(permission_key):
    def decorator(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            if permission_key not in get_user_permissions():
                flash('您没有执行此操作的权限', 'danger')
                return redirect(url_for('auth.login'))
            return f(*args, **kwargs)
        return decorated_function
    return decorator


def get_current_role():
    if hasattr(current_user, "id"):
        role_names = []
        print("#"*100)
        print("is_common_user")
        roles = SysUserRole.query.filter_by(user_id=current_user.id).all()
        print(f"CURRENT_ROLES: {roles}")
        for role in roles:
            print(f"CURRENT_ROLES: {role.role_key}")
            role_names.extend([ x for x in roles_data if x["role_key"] == role.role_key])
        return ",".join([x["role_name"] for x in role_names])
    else:
        return []

def is_common_user():
    if hasattr(current_user, "id"):
        logger.info("#"*100)
        logger.info("is_common_user")
        roles = SysUserRole.query.filter_by(user_id=current_user.id).all()
        logger.info(f"CURRENT_ROLES: {roles}")
        for role in roles:
            logger.info(f"CURRENT_ROLES: {role.role_key}")
            if role.role_key == 'ROLE_USER':
                return True
        return False
    return False

def is_sys_admin():
    if hasattr(current_user, "id"):
        logger.info("#"*100)
        logger.info("is_common_user")
        roles = SysUserRole.query.filter_by(user_id=current_user.id).all()
        logger.info(f"CURRENT_ROLES: {roles}")
        for role in roles:
            logger.info(f"CURRENT_ROLES: {role.role_key}")
            if role.role_key == 'ROLE_SYS_ADMIN':
                return True
        return False
    return False
